﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using blackhouse.BlackApart.Business.Places;
using blackhouse.Locations;
using System.ComponentModel;
using blackhouse.BlackApart.Business;

namespace blackhouse.BlackApart.Web.Modules {
	public partial class ImportantPlaces : System.Web.UI.UserControl {

		#region Fields

		private PlaceDistance distancer;
		private string distanceFormat = "N";
		private DistanceUnit unit = DistanceUnit.Meters;
		private double speed = 7;

		#endregion

		#region Properties

		[Browsable(true)]
		[Category("Places")]
		[DefaultValue(DistanceUnit.Meters)]
		public DistanceUnit Unit {
			get { return this.unit; }
			set { this.unit = value; }
		}

		[Browsable(true)]
		[Category("Places")]
		[DefaultValue("N")]
		public string DistanceFormat {
			get { return this.distanceFormat; }
			set { this.distanceFormat = value; }
		}

		[Browsable(true)]
		[Category("Places")]
		[DefaultValue(7)]
		public double Speed {
			get { return this.speed; }
			set { this.speed = value; }
		}

		[Browsable(true)]
		[Category("Places")]
		public Location ReferenceLocation {
			get;
			set;
		}

		#endregion

		#region Event Handlers

		protected override void OnInit(EventArgs e) {
			base.OnInit(e);

			this.rptPlaces.ItemCreated += new RepeaterItemEventHandler(ItemCreated_rptPlaces);
		}

		protected override void OnLoad(EventArgs e) {
			base.OnLoad(e);

			this.SetInstance();
			this.PopulateControls();
		}

		#endregion

		#region Methods

		private void SetInstance() {
			this.distancer = new PlaceDistance(this.ReferenceLocation, this.Unit);
			this.distancer.AddRange(Factory.Instance().GetPlace().GetAllPlaces());
			this.distancer.SortByDistance();
		}

		private void PopulateControls() {
			this.rptPlaces.DataSource = this.distancer.GetDistinctCategories();
			this.rptPlaces.DataBind();
		}

		private void ItemCreated_rptPlaces(object sender, RepeaterItemEventArgs e) {
			if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
				string category = e.Item.DataItem.ToString();
				ImportantPlacesItemTemplate itemTemplate = e.Item.FindControl("ImportantPlacesItemTemplate1") as ImportantPlacesItemTemplate;
				if (!string.IsNullOrEmpty(category) && itemTemplate != null) {
					itemTemplate.PopulateControl(this.distancer.GetPlacesByCategory(category), this.distancer, this.DistanceFormat, this.Speed);
				}
			}
		}

		#endregion

	}
}